package net.lovesrc.allin.biz.user;

import com.alibaba.fastjson.JSONObject;
import net.lovesrc.allin.bo.User;
import net.lovesrc.allin.exception.AuthcationException;
import net.lovesrc.support.service.JdbcTemplateSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
class UserServiceImpl extends JdbcTemplateSupport implements UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public User verify(String id, String password) throws AuthcationException {

        User user = getById(id);
        if (user == null) {
            throw new AuthcationException(id + " not exists");
        }
        if (!user.getPassword().equals(password)) {
            throw new AuthcationException("password not match");
        }
        String hashStr = UUID.randomUUID().toString();
        insertRow(
                jdbcTemplate,
                "t_user_hash_str",
                new JSONObject()
                        .fluentPut("id", hashStr)
                        .fluentPut("userId", id)
        );
        user.setHashStr(hashStr);
        return user;
    }

    @Override
    public User verify(String hashStr) {

        JSONObject userHash = queryForRow(jdbcTemplate, "select * from t_user_hash_str where id = ?", hashStr);
        if (userHash == null) {
            return null;
        }
        String userId = userHash.getString("userId");
        return getById(userId);
    }

    @Override
    public User getById(String id) {

        return findOne(jdbcTemplate, User.class, "select * from t_user where id = ?", id);
    }


}
